import JSZip from 'jszip'

export function downloadFiles (urls, zipName = 'files.zip') {
  const zip = new JSZip()

  const downloadPromises = urls.map(item => {
    return fetch(item.url)
      .then(response => response.blob())
      .then(blob => {
        // 将文件添加到zip
        const filename = getFilenameFromUrl(item.name)
        zip.file(filename, blob)
      })
  })

  Promise.all(downloadPromises)
    .then(() => {
      // 生成zip文件
      return zip.generateAsync({ type: 'blob' })
    })
    .then(blob => {
      // 下载zip文件
      const zipFilename = zipName
      downloadBlob(blob, zipFilename)
    })
}

function getFilenameFromUrl (url) {
  // 从url中获取文件名
  const lastSlashIndex = url.lastIndexOf('/')
  return url.substring(lastSlashIndex + 1)
}

function downloadBlob (blob, filename) {
  // 创建一个URL对象
  const url = URL.createObjectURL(blob)

  // 创建一个<a>标签
  const link = document.createElement('a')
  link.href = url
  link.download = filename
  link.style.display = 'none'

  // 添加到文档中并模拟点击
  document.body.appendChild(link)
  link.click()

  // 清理URL对象
  URL.revokeObjectURL(url)

  // 删除<a>标签
  document.body.removeChild(link)
}